import { Ref, useContext, useRef, useState } from 'react';
import { RegularExpression } from '@/common/constVariable';
import { OneModal } from '@/components/one-ui';
import { Col, Form, Input, Row, Spin, message, Select, List, Empty, Table } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { IOneModalRef } from '@/pages/type';
import { ContractManageAPI } from '../common/type';
import Cls from 'classnames';
import { ConractControllerContext } from '../common';
import { onCloseModalCommon, getKeyRouter } from '@/utils';
import { addCounterpartService, SelectBankService } from '../services';
import InfiniteScroll from 'react-infinite-scroller';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { UploadFormCommon } from '@/components/UploadForm';
import { UpdateTableFullNameColumns } from '../mconfig';
import _ from 'lodash';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';

export const OpenCounterpartModalForm: React.FC<ContractManageAPI.IOpenCounterpartModalForm> = ({ onClose, reloadManage }) => {
  /** 添加相对方表单 */
  const [counterForm] = Form.useForm();

  /** 企业属性标记 */
  const [enterType, setEnterType] = useState(0);

  /** 表格数据源 */
  const [tableData, setTableData] = useState<Record<string, any>[]>([{ id: getKeyRouter() }]);

  /** 弹框ref */
  const counterFormModalRef: Ref<IOneModalRef> = useRef(null);

  /** 引入上下文 */
  const { styleFixCls } = useContext(ConractControllerContext);

  /** 接口回调 */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModalCommon(counterFormModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加相对方接口 */
  const { addCounterpartLoading, addCounterpartRun } = addCounterpartService(updateCallback);

  /** 保存按钮 */
  const onSave = () => {
    counterForm?.validateFields()?.then((values: any) => {
      const payload: Record<string, any> = {
        ...values,
        contactName: values?.table?.[0]?.fullName, //首要联系人姓名
        contactMobile: values?.table?.[0]?.phoneMobile, //首要联系人电话
      };
      // 判断table长度，除去第一项是首要联系人，剩下的是添加的
      if (values?.table?.length > 1) {
        const newTableData = values?.table?.filter((_item, index) => index != 0);
        payload.msupplierContacterList = newTableData;
      } else {
        payload.msupplierContacterList = null;
      }
      // 删除表格数据
      delete payload['table'];
      addCounterpartRun(payload);
    });
  };

  /** 保存的分页参数 */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 1,
    loading: false,
    hasMore: true,
    limit: 10,
  });

  /**
   * 获取数据
   * */
  const { loading: bankLoading, getBankRun, reloadRefresh, data, pagination } = SelectBankService((res) => {
    if (res && res?.msgFlag) {
      // setManageDataList(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        total: res.total,
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 初始化获取数据 */
  const defaultGetWarnData = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,
      count: count,
      loading: true,
    });
    let payload = {
      current: 1,
      pageSize: count * 10 + limit,
      bankName: searchVal,
    };
    getBankRun(payload);
  };

  /** 滚动加载 */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (Number(data?.rows?.length) >= total) {
      message.warning('没有更多数据了！');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetWarnData();
  };

  /** 数据值 */
  const [searchVal, setSearchVal] = useState<string | undefined>();
  /** 开户行select受控模式 */
  const [open, setOpen] = useState(false);

  /** 表格内按钮点击方法 */
  const onTableClick = (type, dataIndex) => {
    if (type === 'add') {
      if (typeof tableData === 'undefined') {
        setTableData([{ id: getKeyRouter() }]);
      } else {
        let newtableData = _?.cloneDeep(tableData);
        newtableData?.push({ id: getKeyRouter() });
        setTableData(newtableData);
      }
    } else if (type === 'delete') {
      const tablePropsVal = counterForm?.getFieldValue('table');
      const tablePropsVals = _?.cloneDeep(tablePropsVal);
      tablePropsVals?.splice(dataIndex, 1);
      counterForm?.setFieldsValue({
        table: tablePropsVals,
      });
      if (typeof tablePropsVal === 'undefined') {
        setTableData([{ id: getKeyRouter() }]);
      } else {
        setTableData(tablePropsVals);
      }
    }
  };

  return (
    <OneModal
      open={true}
      title="添加相对方"
      getContainer={false}
      ref={counterFormModalRef}
      onCancel={onClose}
      width={document.body.clientWidth * 0.8}
      bodyStyle={{
        padding: '8px 2px',
      }}
      onOk={onSave}
      confirmLoading={addCounterpartLoading}
      formModalType={true}
    >
      <Spin spinning={addCounterpartLoading}>
        <div className={Cls(pageStyles['fromView-styles'], `${styleFixCls}updateFormBox`)}>
          <Form form={counterForm}>
            {/* <div className={`supplierFormLabel-minBoxTitle`}>单位信息</div> */}
            <TypographyTitle children={'单位信息'} level={5} />

            <Row>
              <Col span={12}>
                <Form.Item
                  name="fullName"
                  label="单位名称"
                  rules={[
                    {
                      required: true,
                      message: '请输入单位名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入单位名称" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                {/* <Form.Item label="单位简称" name="shortName">
                        <Input placeholder="请输入" allowClear />
                      </Form.Item> */}
                <TagSelect
                  formLabel="企业属性"
                  formName="enterpriseType"
                  formRequired={true}
                  radioList={[
                    {
                      value: 0,
                      name: '大陆',
                    },
                    {
                      value: 1,
                      name: '港澳台',
                    },
                    {
                      value: 2,
                      name: '境外',
                    },
                  ]}
                  defalultKeys={0}
                  onChange={(valNum) => {
                    setEnterType(valNum);
                    if (valNum) {
                      counterForm?.validateFields();
                    }
                  }}
                />
              </Col>
              <Col span={12}>
                <Form.Item
                  name="legalName"
                  label="法定代表人"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请输入法定代表人',
                          },
                        ]
                  }
                >
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="所属区域" name="registerAddress">
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={enterType ? '企业注册代码' : '统一社会信用代码'}
                  name="creditID"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请输入' + (enterType ? '企业注册代码' : '统一社会信用代码'),
                          },
                        ]
                  }
                >
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label="注册电话"
                  name="registerPhone"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请输入注册电话',
                          },
                        ]
                  }
                >
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label="开户行名称"
                  name="bankName"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请选择开户行',
                          },
                        ]
                  }
                >
                  {/* <Input
                          placeholder="请选择"
                          disabled
                          addonAfter={
                            <Tooltip title="点击选择开户行">
                              <a>
                                <SearchOutlined className={pageStyles['mouseChangeHands']} onClick={clickSearchBank} />
                              </a>
                            </Tooltip>
                          }
                        /> */}

                  <Select
                    open={open}
                    onDropdownVisibleChange={(visible) => setOpen(visible)}
                    allowClear
                    showSearch
                    onSearch={_?.debounce((val) => {
                      if (val) {
                        setSearchVal(val);
                        getBankRun({ current: 1, pageSize: 10, bankName: val?.split(' ')?.join(',') });
                        setScrollObj({
                          ...scrollObj,
                          count: 1,
                          // loading: true,
                        });
                      } else {
                        setSearchVal(undefined);
                        getBankRun({ current: 1, pageSize: 10 });
                        setScrollObj({
                          ...scrollObj,
                          count: 1,
                          // loading: true,
                        });
                      }
                    }, 1000)}
                    onClear={() => {
                      counterForm?.setFieldValue('bankCode', undefined);
                      getBankRun({ current: 1, pageSize: 10 });
                      setScrollObj({
                        ...scrollObj,
                        count: 1,
                        // loading: true,
                      });
                    }}
                    onSelect={(val, node) => counterForm?.setFieldValue('bankCode', node?.key)}
                    filterOption={false}
                    placeholder={'请选择(多关键字用空格隔开)'}
                    // notFoundContent={!scrollObj?.loading && scrollObj?.hasMore ? <Spin size="small" /> : null} // 加载状态提示
                    dropdownRender={(menu) => (
                      <div className={'bankSelectScrollBox'} style={{ width: '100%', height: '300px' }}>
                        <InfiniteScroll
                          loadMore={handleInfiniteOnLoad}
                          initialLoad={false}
                          pageStart={1}
                          useWindow={false}
                          hasMore={!scrollObj?.loading && scrollObj?.hasMore}
                          loader={
                            <div style={{ textAlign: 'center' }}>
                              <Spin size="small" spinning={bankLoading} />
                            </div>
                          }
                        >
                          <div className="commonTabsBodyDom">
                            {data?.rows?.length ? (
                              <div style={{ padding: '0px 5px', cursor: 'pointer' }}>
                                <List
                                  itemLayout="horizontal"
                                  dataSource={data?.rows}
                                  renderItem={(item: Record<string, any>) => {
                                    return (
                                      <List.Item
                                        onClick={() => {
                                          console.log('item.bankName', item?.bankName);
                                          console.log('item.bankCode', item?.bankCode);
                                          counterForm?.setFieldsValue({
                                            bankName: item?.bankName,
                                            bankCode: item?.bankCode,
                                          });
                                          setOpen(false);
                                        }}
                                      >
                                        <List.Item.Meta title={item?.bankName} />
                                      </List.Item>
                                    );
                                  }}
                                />
                              </div>
                            ) : (
                              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                            )}
                          </div>
                        </InfiniteScroll>
                      </div>
                    )}
                    options={data?.rows?.map((item) => ({ label: item.bankName, value: item?.bankCode }))}
                  ></Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="开户行账号"
                  name="bankAccount"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请输入开户行账号',
                          },
                        ]
                  }
                >
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="银行行号"
                  name="bankCode"
                  // rules={[
                  //   {
                  //     required: true,
                  //     message: '请选择开户行',
                  //   },
                  // ]}
                >
                  <Input placeholder="自动带出" disabled />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label="单位地址"
                  name="workAddress"
                  rules={
                    enterType
                      ? undefined
                      : [
                          {
                            required: true,
                            message: '请选择单位地址',
                          },
                        ]
                  }
                >
                  <Input placeholder="请输入" allowClear />
                </Form.Item>
              </Col>
              <UploadFormCommon
                form={counterForm}
                fileFormName={'licenceURL'}
                spanCol={24}
                inRowProportion={24}
                name={'attachFile'}
                url={'/supplierInfoController/uploadFile'}
                downloadUrl={'/supplierInfoController/downloadFile'}
                label="营业执照"
                required={false}
                accept={'.jpg|.png|.jpeg'}
                fileFormDelName={'licenceURLDel'}
                delFunc={() => {}}
                maxFile={1}
                fieldBusiPath={'supplier/info'}
                defaultFiles={null}
              >
                营业执照
              </UploadFormCommon>
              {/* <Col span={12}>
                <Form.Item
                  name="registerPhone"
                  label="单位电话"
                  rules={[
                    {
                      required: true,
                      message: '请输入单位电话',
                    },
                    // {
                    //   pattern: RegularExpression.fixedPhone,
                    //   message: '单位电话格式不准确',
                    // },
                    // () => ({
                    //   validator(_, value) {
                    //     if (RegularExpression.fixedPhone.test(value) || RegularExpression.phone.test(value)) {
                    //       return Promise.resolve();
                    //     }
                    //     return Promise.reject(new Error('单位电话格式不准确'));
                    //   },
                    // }),
                  ]}
                >
                  <Input placeholder="请输入单位电话" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="contactName"
                  label="联系人姓名"
                  rules={[
                    {
                      required: true,
                      message: '请输入联系人姓名',
                    },
                  ]}
                >
                  <Input placeholder="请输入联系人姓名" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  // name="phoneMobile"
                  name="contactMobile"
                  label="联系电话"
                  rules={[
                    {
                      required: true,
                      message: '请输入联系电话',
                    },
                    // {
                    //   pattern: RegularExpression.phone,
                    //   message: '联系电话格式不准确',
                    // },
                    // () => ({
                    //   validator(_, value) {
                    //     if (RegularExpression.fixedPhone.test(value) || RegularExpression.phone.test(value)) {
                    //       return Promise.resolve();
                    //     }
                    //     return Promise.reject(new Error('单位电话格式不准确'));
                    //   },
                    // }),
                  ]}
                >
                  <Input placeholder="请输入联系电话" allowClear />
                </Form.Item>
              </Col> */}
              {/* <Col span={12}>
                <Form.Item
                  name="phoneOffice"
                  label="办公手机"
                  rules={[
                    {
                      pattern: RegularExpression.workPhone,
                      message: '办公手机格式不准确',
                    },
                  ]}
                >
                  <Input placeholder="请输入办公手机" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phoneSpare"
                  label="备用手机"
                  rules={[
                    {
                      pattern: RegularExpression.workPhone,
                      message: '备用手机格式不准确',
                    },
                  ]}
                >
                  <Input placeholder="请输入备用手机" allowClear />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="emailNum"
                  label="邮箱地址"
                  rules={[
                    {
                      pattern: RegularExpression.email,
                      message: '邮箱地址格式不准确',
                    },
                  ]}
                >
                  <Input placeholder="请输入邮箱地址" allowClear />
                </Form.Item>
              </Col> */}
              {/* <Col span={24}>
              <Form.Item name="remark" label="备注">
                <Input.TextArea
                  placeholder="请输入备注"
                  allowClear
                  showCount
                  maxLength={200}
                  autoSize={{ minRows: 2, maxRows: 3 }}
                />
              </Form.Item>
            </Col> */}
            </Row>
            {/* <div className={`supplierFormLabel-minBoxTitle`}>联系人信息</div> */}
            <TypographyTitle children={'联系人信息'} level={5} />

            <div className="list-table">
              <Form.Item name="table" valuePropName="tableData">
                <Table bordered size={'small'} pagination={false} dataSource={tableData} columns={UpdateTableFullNameColumns(onTableClick, enterType)} />
              </Form.Item>
            </div>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
